package com.lw.extraceim.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;

import com.google.gson.reflect.TypeToken;
import com.lw.extraceim.R;
import com.lw.extraceim.app.ExtraceCfg;
import com.lw.extraceim.loader.UserLoader;
import com.lw.extraceim.model.UserInfo;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.TextUtil;

import org.json.JSONException;

import okhttp3.Call;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    /*找到所有的控件*/
    private Button mBtLogin, mBtSign;
    private EditText mEtLoginPhone, mEtLoginPass;
    private CheckBox mCbRemeberMe;
    private String userName, userPass;
    private TextView mTvForgetPwd;
    protected ProgressDialog progressDialog;

    private String phone;
    private String password;
    private ExtraceCfg extraceCfg;
    private UserLoader userLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_login);
        //透明状态栏          
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        actionBar.hide(); //隐藏actionBar
        //找到所有的控件
        mBtLogin = findViewById(R.id.bt_login);
        mBtSign = findViewById(R.id.bt_sign);
        mEtLoginPhone = findViewById(R.id.et_login_phone);
        mEtLoginPass = findViewById(R.id.et_login_pass);
        mCbRemeberMe = findViewById(R.id.cb_remember_me);
        mTvForgetPwd = findViewById(R.id.tv_forget_pwd);

        progressDialog = new ProgressDialog(this);
    }

    @Override
    public void initData() {
        extraceCfg = application.getExtraceCfg();
        userLoader = new UserLoader(this);
    }

    @Override
    public void refreshUI() {
        Log.d(TAG, "refreshUI: " + application.getExtraceCfg());
        Log.d(TAG, "refreshUI: " + application.getExtraceCfg().getUserLoginInfo());
        if (application.getExtraceCfg().isRememberMe()) {
            mCbRemeberMe.setChecked(extraceCfg.isRememberMe());
            mEtLoginPhone.setText(extraceCfg.getUserLoginInfo().phone);
            mEtLoginPass.setText(extraceCfg.getUserLoginInfo().password);
        }
    }

    @Override
    public void initEvent() {
        //为注册按钮设置监听事件
        mBtSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转界面
                Intent intent = new Intent(LoginActivity.this, SignActivity.class);
                startActivity(intent);
            }
        });
        //为登录按钮注册事件
        mBtLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeLoginButton("正在登录。。", false);
                login(); //登录
            }
        });
        mTvForgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, FindPassActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 登录
     */
    public void login() {

        if (checkInput()) {
            userLoader.login(phone, password, new HttpResponseParamCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    alert("网络错误" + e.getMessage());
                    changeLoginButton("登录", true);
                }

                @Override
                public void onResponse(HttpResponseParam response, int id) {
                    if (response.code.getCode() == ResponseCode.SUCESS) {
                        try {
                            String sessionId = response.reseponseJson.getString("sessionId");
                            UserInfo userInfo = JsonUtils.fromJson(response.reseponseJson.getJSONObject("user").toString(), new TypeToken<UserInfo>() {
                            });
                            if (userInfo == null) {
                                alert("登录失败");
                            } else {
                                Log.d(TAG, "onResponse: 登录成功" + userInfo + "\n"
                                        + "sessionId=" + sessionId);
                                application.setUserInfo(userInfo);
                                application.setSessionId(sessionId);
                                //判断记住我是否被选中
                                if (mCbRemeberMe.isChecked()) {
                                    application.getExtraceCfg().setRememberMe(true);
                                    application.getExtraceCfg().setAutoLogin(false);
                                    application.getExtraceCfg().setUserLoginInfo(phone,password);
                                    application.saveExtraceCfg();
                                }
                                MainActivity.actionStart(LoginActivity.this);
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        alert("账号或密码错误");
                    }
                    changeLoginButton("登录", true);
                }
            });
        } else {
            changeLoginButton("登录", true);
        }
    }

    /**
     * 检查输入是否正确
     *
     * @return
     */
    public boolean checkInput() {
        phone = mEtLoginPhone.getText().toString().trim();
        if (TextUtil.isNull(phone) || !TextUtil.isPhone(phone)) {
            toast("电话号码格式错误！");
            return false;
        }
        password = mEtLoginPass.getText().toString();
        if (TextUtil.isNull(password)) {
            return false;
        }
        return true;
    }

    /**
     * 修改登录按钮的文字和是否能够点击
     *
     * @param text
     * @param enable
     */
    public void changeLoginButton(String text, boolean enable) {
        mBtLogin.setText(text);
        mBtLogin.setEnabled(enable);
    }



    public static void actionStart(Context context){
        Intent intent = new Intent(context,LoginActivity.class);
        context.startActivity(intent);
    }
}


